// pages/_middleware.js
import { NextResponse, NextRequest } from 'next/server'
import { IsneedToken } from './app/api/cofing'
import { verifyToken } from './util/jwt'
//中间件
export function middleware(request: NextRequest) {
  const headerKey = process.env.HEADER_TOKEN
  const env = process.env.NODE_ENV == 'production'
  const bol = checkJWt(
    request.nextUrl.pathname,
    request.headers.get(headerKey as string)
  )
  if (env && !bol) {
    // 生产环境
    return NextResponse.redirect(new URL('/', request.url))
  }
  if (env && !bol) {
    // 开发环境
    console.warn('未登录,token校验失败')
    return NextResponse.json({ code: 401, msg: '未登录' })
  }
  return NextResponse.next()
}

function checkJWt(path: string, header: string | null): boolean | object {
  console.log('header', header)

  if (!IsneedToken(path)) {
    return true
  }
  if (!header) {
    return false
  }
  const info = verifyToken(header)
  if (!info) {
    return false
  }
  // 验证jwt
  return true
}
